package top.tagao.service_oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.tagao.service_oss.service.FileService;
import top.tagao.service_oss.utils.ConstantOssPropertiesUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author fu-xiao-liu
 * @Date 2022/3/12 10:44
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {


    /**
     * @param file
     * @return java.lang.String
     * @date 图片上传到OSS
     */
    @Override
    public String upload(MultipartFile file) {
        String endpoint = ConstantOssPropertiesUtils.EDNPOINT;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtils.SECRECT;
        String bucketName = ConstantOssPropertiesUtils.BUCKET;

        try {
            log.info("ACCESS_KEY_ID : {}" ,accessKeyId);
            // 1. 创建OSSClient 实例
            OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 2. 生成文件流
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            // 3. 使用uuid,拼接文件名称
            fileName = UUID.randomUUID().toString().replace("-", "")  + fileName ;
            // 4. 生成文件夹
            String mkdir = new DateTime().toString("yyyy/MM/dd");
            fileName = mkdir + "/" + fileName;

            // 5. 上传文件
            oss.putObject(bucketName,fileName,inputStream);
            // 6. 关闭OSSClient
            oss.shutdown();

            String url =   "https://"+bucketName+"."+endpoint+"/"+fileName;

            return url;

        } catch (IOException e) {
            e.printStackTrace();
        }


        return null;
    }
}
